package com.hn.zhijian.web.websocket;

import com.alibaba.fastjson.JSON;
import com.hn.zhijian.base.common.StatusCode;
import com.hn.zhijian.base.model.response.Response;
import com.hn.zhijian.utils.Utils;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author carl chen
 * @Classname GhglWebSocket
 * @Description 服务端跟客服端进行通讯
 * @Date 2019/11/11 15:51
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Api("web socket  /websocket userId = 用户账号编号")
public class WebSocketServer {

    private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接受客服端编号
     */
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {

        this.sid = userId;
        this.session = session;

        //加入set中
        webSocketSet.put(session.getId(), this);

        logger.info("有一连接加入！当前在线人数为" + getOnlineCount());
        //在线数加1
//        addOnlineCount();

//        try {
//            sendMessage(JSON.toJSONString(WebSocketServer.getMessageObject(StatusCode.OK.getMessage())));
//        } catch (IOException e) {
//            logger.error("websocket IO异常");
//        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        logger.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("收到来自窗口" + sid + "的信息:" + message);
        //群发消息
//        for (WebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    private static Response getMessageObject(Object ojb){
        Response response = new Response();
        response.setBody(ojb);
        response.setCode(StatusCode.OK.getCode());
        response.setMessage(StatusCode.OK.getMessage());
        return response;
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(Object ojb, @PathParam("sid") String sid) throws IOException {

        Response response = getMessageObject(ojb);

        logger.info("推送消息到窗口" + sid + "，推送内容:" + JSON.toJSONString(ojb));
        //如果sid不为空发送单个信息，如果为空发送所有客服端消息
        try {
            if (Utils.isEmpty(sid)) {
                for (String key : webSocketSet.keySet()) {

                    WebSocketServer server = webSocketSet.get(key);

                    if (Utils.notEmpty(server)) {
                        try{
                            server.sendMessage(JSON.toJSONString(response));
                        }catch (Exception e){
                            webSocketSet.remove(key);
                            logger.info("推送消息到窗口" + sid + "，推送内容失败:" + JSON.toJSONString(ojb));
                        }
                    }
                }
            } else {
                WebSocketServer server = webSocketSet.get(sid);
                if (Utils.notEmpty(server)) {
                    try{
                        server.sendMessage(JSON.toJSONString(response));
                    }catch (Exception e){
                        logger.info("推送消息到窗口" + sid + "，推送内容失败:" + JSON.toJSONString(ojb));
                    }
                }
            }
        } catch (Exception e) {
            logger.info("推送消息到窗口" + sid + "，推送内容失败:" + JSON.toJSONString(ojb));
        }
    }

    public static synchronized int getOnlineCount() {
        return webSocketSet.size();
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
